package com.briup.run.util;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Auther: vanse(lc))
 * @Date: 2022/10/10-10-10-15:24
 * @Description：com.briup.run.util
 * https://www.36ip.cn/?ip=180.101.49.11
 * 响应 真实地址
 */
public class IpUtil {

    // // 获取Ip地址 防止代理ip
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader(" x-forwarded-for ");
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
            ip = request.getHeader(" Proxy-Client-IP ");
        }
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
            ip = request.getHeader(" WL-Proxy-Client-IP ");
        }
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    /**
     *
     * @param ip ip地址  180.101.49.11
     * @return 真实的地址  江苏南京 电信
     */
    public static String getReadAdd(String ip){
        // ipv4地址 本机
        if("127.0.0.1".equals(ip)){
            return "本机地址 杰普";
        }
        BufferedReader br = null;
        try {
            URL url = new URL("https://www.36ip.cn/?ip="+ip);
            // 通过代码 发送连接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            // 接收响应
            br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String result = br.readLine();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String readAdd = getReadAdd("172.16.0.4");
        System.out.println("readAdd = " + readAdd);
    }
}
